﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WeChat.JsSDK;
using Newtonsoft.Json.Linq;
using BLL;
using WeChat.Common2;

namespace WeChat.Common
{
    public class OAuthHelper
    {
        /*=======================OAuth2.0认证=====================*/
        //只需要snsapi_base获取用户openid即可
        //重定向url,scope=snsapi_base
        public static string getRedirectUrl(string url)
        {
            string redirect_uri = HttpUtility.UrlEncode(url);
            return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", GetSdkParams.getAppId(), redirect_uri, GetSdkParams.getNonceStr(16));
        }
        //获取用户openid
        public static string getOpenid(string code)
        {
            GetReturnJson gt = new GetReturnJson();
            string secret = Config.getAppSecret();//ConfigurationSettings.AppSettings["appSecret"].ToString();
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", GetSdkParams.getAppId(),secret,code);

            string reJson = gt.getReturnJson(url);
            JObject jo = JObject.Parse(reJson);
            if (!reJson.Contains("errcode"))
            {
                string openid = jo["openid"].ToString();
                BindIdBLL bi = new BindIdBLL();
                if (bi.verifyId(openid))   //验证用户是否绑定账号
                {
                    //ApplicationLog.Write("用户OAuth2.0授权验证,用户已绑定。openid：" + openid);
                }
                return openid;
            }
            else
            {
                ApplicationLog.Write("用户OAuth2.0授权验证,用户未绑定。" + reJson);
                return "";
            }
        }
    }
}
